package com.jxm.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jxm.common.Constants;
import com.jxm.exception.ApiInvokeException;
import com.jxm.interceptor.ExceptionInterceptor;
import com.jxm.model.User;
import com.jxm.vo.IResult;

public class UserService {
	
	public IResult login(String username){
		if(User.dao.usernameIsExist(username)){
	    	return IResult.succuss();
	     }
		return IResult.failed("用户名错误");
		
	}
	
	public Page<User> getPage(int page,int pageSize,String username){
		StringBuilder builder = new StringBuilder("from user where 1 = 1 ");
		List<Object> params = new ArrayList<Object>();
		if(StrKit.notBlank(username)){
			builder.append("and username like ?");
			params.add("%"+username+"%");
		}
		builder.append(" order by create_time desc");
		return User.dao.paginate(page, pageSize, "select *",builder.toString(),params.toArray());
	}
	
	public IResult save(String username,Integer sex ,Integer status,String remark){
		User user = new User();
		user.setUsername(username);
		user.setSex(sex);
		user.setStatus(status);
		user.setRemark(remark);
		user.setCreateTime(new Date());
		user.save();
		return IResult.succuss();
	}
	
	
	
	public User findById(Integer id){
		return User.dao.findById(id);
	}

	public IResult update(Integer id, Integer sex, String remark, Integer status) {
		User user = User.dao.findById(id);
		user.setSex(sex);
		user.setStatus(status);
		user.setRemark(remark);
		user.update();
		return IResult.succuss();
	}

	public IResult delte(Integer id) {
		User.dao.deleteById(id);
		return IResult.succuss();
	}
	
//	@Before(ExceptionInterceptor.class)
	public IResult lock(Integer id) {
		//测试异常
//		if(id<1000){
//			throw new ApiInvokeException("用户id不存在");
//		}
		User user = User.dao.findById(id);
		user.setStatus(Constants.LOCL_STATUS);
		user.update();
		return IResult.succuss();
	}

	public IResult unlock(Integer id) {
		User user = User.dao.findById(id);
		user.setStatus(Constants.NORMAL_STATUS);
		user.update();
		return IResult.succuss();
	}
}
